#include "bookdata.h"

BookData::BookData():contents(new QVector<QString>),indexes(new QVector<QString>)
{
}
BookData::BookData(const QString &file):contents(new QVector<QString>),indexes(new QVector<QString>)
{
    fileName = file;
    loadFromFile(file);
}
void BookData::loadFromFile(const QString &filename)
{
    if(filename.endsWith(".zip")){
        loadFromZipFile(filename);
        return;
    }
    QFile file(filename);
    if ( file.open(QFile::ReadOnly )) {
        contents->clear();
        fileName = filename;

        QTextStream stream( &file );
        QString lines;
        QString line;

        int count = 0;
        while(!stream.atEnd()){
            line = stream.readLine();
            line.append("<br/>");
            lines.append(line);
            count=count+(line.count()/31)+1;
            if(count>=60){
                count=0;
                contents->append(lines);
                lines.clear();
            }
        }
        file.close();
        addCover();
    }
}
void BookData::loadFromZipFile(const QString &filename)
{
    QString exePath = QCoreApplication::applicationDirPath ();
    QMessageBox::about(0,"",exePath);
    QDir dir(exePath+"\\cache");
    dir.setCurrent(exePath+"\\cache");

    QFileInfo fileInfo(filename);
    QMessageBox::about(0,"",exePath+"\\cache\\"+fileInfo.fileName().left(fileInfo.fileName().indexOf(".")));
    dir.mkdir(exePath+"\\cache\\"+fileInfo.fileName().left(fileInfo.fileName().indexOf(".")));
    QZip zip(filename,exePath+"\\cache\\"+fileInfo.fileName().left(fileInfo.fileName().indexOf(".")));
    zip.unzip();
}
QVector<QString>* BookData::getContents()
{
    return contents;
}
void BookData::addCover()
{
    Util util;
    QString content = util.loadFile("template\\cover.html");
    QFileInfo fileInfo(fileName);

    content = content.replace("${title}",fileInfo.fileName());
    content = content.replace("${author}",fileInfo.owner());
    content = content.replace("${discription}",QString("Total Page %1").arg(contents->count()));

    QDateTime date = fileInfo.created();
    content = content.replace("${date}",date.toString());
    contents->insert(contents->begin(),content);
}

